<template>
  <div class="login-container">
    <div class="title">省体育局系统</div>
    <div>
      <div class="top-icon">
        <svg-icon icon-class="user" />
      </div>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on"
        label-position="top">
        <div style="margin-bottom: 10px;display: inline-block;margin-right: 10px;">手机号</div>
        <span v-html="idInfo"></span>
        <el-form-item prop="username" :style="!usernamevalid?'':{'border-color':'red'}">
          <el-input ref="username" v-model.trim="loginForm.username" placeholder="手机号" name="username" type="text"
            tabindex="1" auto-complete="on" />
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
        </el-form-item>
        <el-button v-if="!countdown" @click.stop.native="getCode" type="success" size="mini"
          style="width:100px;margin-left: auto;float: right;">获取验证码</el-button>
        <div v-else style="width:20px;margin-left: auto;float: right;">{{countdown}}</div>
        <div style="font-size: 10rpx;color: #B94A48;" v-html="codeMsg"></div>
        <div :style="codeMsg?{'margin-top':'30px'}:''" style="margin-top: 60px;margin-bottom: 10px;">{{pwdOrCodeText}}
        </div>
        <el-form-item prop="password" :style="!passwordvalid?'':{'border-color':'red'}" :error="errorMsg">
          <el-input :key="passwordType" ref="password" v-model.trim="loginForm.password" :type="passwordType"
            :placeholder="pwdOrCodeText" name="password" tabindex="2" auto-complete="on"
            @keyup.enter.native="handleLogin" />
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
        <el-checkbox style="margin-top: 10px;" v-model="remember">记住我</el-checkbox>
        <div v-show="false">
          <div class="border"></div>
          <div style="display: flex;margin-top: 20px;">
            <div style="width: 80px;" :style="roleColor?{'color':'red'}:''">选定一个角色登录</div>
            <el-radio-group v-model="roleRadio" style="display: flex;flex-direction: column;margin-left: 30px;">
              <el-radio style="margin-bottom:10px;" v-for="(item,index) in roleData" :key="index" :label="item.roleId">
                {{dict_role[item.roleId%14]}}
              </el-radio>
            </el-radio-group>
          </div>
        </div>
        <el-button :loading="loading" type="success" style="width:100px;margin-bottom:30px;float: right;"
          @click.native.prevent="handleLogin">登录</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
  import { validUsername, validPassword } from '@/utils/validate'
  import { userInfo, roleIdsByLoginStr, login, sendSms } from '@/api/user.js'
  import getDefaultState from '@/store/modules/user.js'
  import { setRemember, getRemember, removeRemember } from '@/utils/auth'
  import {
    area2playerId,
  } from '@/api/statistics.js'

  export default {
    name: 'Login',
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!validUsername(value)) {
          this.usernamevalid = true
          callback(new Error('请输入正确的用户名'))
        } else {
          const userName = { userName: value }
          userInfo(userName).then(res => {
            this.idInfo = res.data
            if (res.code === 200) {
              window.localStorage.setItem('userInfo', res.data)
              // 请求权限
              const loginStr = { loginStr: value }
              roleIdsByLoginStr(loginStr).then(role => {
                if (role.code === 200) {
                  // console.log(role, "ssssssssss");
                  this.roleData = role.data
                  this.userId = role.data[0].userId
                  this.roleRadio = role.data[0].roleId
                  console.log(this.userId, "888888888");
                  this.$store.dispatch('user/getMenu', { userId: this.userId, roleId: this.roleRadio })

                }
              })
            } else {
              this.roleData = []
            }
          })
          this.usernamevalid = false
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (!validPassword(value)) {
          this.passwordvalid = true
          callback(new Error('请输入正确的密码'))
        } else {
          this.passwordvalid = false
          callback()
        }
      }
      return {
        loginForm: {
          username: '',
          password: '',
          messageCode: ''
        },
        loginRules: {
          username: [{ required: true, trigger: 'click', validator: validateUsername }],
          password: [{ required: true, trigger: 'click', validator: validatePassword }]
        },
        loading: false,
        passwordType: 'password',
        redirect: undefined,
        usernamevalid: false,
        passwordvalid: false,
        roleRadio: '',
        idInfo: '',
        roleData: [],
        userId: '',
        dict_role: getDefaultState.state.dict_role,
        roleColor: false,
        code: '',
        errorMsg: '',
        codeMsg: '',
        pwdOrCodeText: '密码',
        countdown: '',
        remember: false,
        dict_player: [],
      }
    },
    watch: {
      $route: {
        handler: function(route) {
          this.redirect = route.query && route.query.redirect
        },
        immediate: true
      },
      roleRadio(val) {
        if (val) {
          this.roleColor = false
        }
      },
      'loginForm.username': {
        deep: true,
        handler: function(val) {
          if (val) {
            this.loginRules.username[0].trigger = 'blur'
          }
        }
      },
      'loginForm.password': {
        deep: true,
        handler: function(val) {
          if (val) {
            this.loginRules.password[0].trigger = 'blur'
          }
        }
      }
    },
    created() {
      // let uname = getRemember('username')
      // let upwd = getRemember('password')
      let uname = window.localStorage.getItem('username')
      let upwd = window.localStorage.getItem('password')
      if (uname) {
        this.loginForm.username = uname
        this.remember = true
      }
      if (upwd) {
        this.loginForm.password = upwd
      }
    },
    methods: {
      getCode() {
        let userName = this.loginForm.username
        let phone_reg = /^[1][3,4,5,7,8][0-9]{9}$/
        if (phone_reg.test(userName)) {
          sendSms({ phoneNumber: userName }).then(res => {
            if (res.code === 200) {
              this.pwdOrCodeText = '验证码'
              this.codeMsg = ''
              this.countdown = 60
              let timer = setInterval(() => {
                this.countdown -= 1
                if (this.countdown == 0) {
                  this.countdown = ''
                  clearInterval(timer)
                }
              }, 1000)
            } else {
              this.codeMsg = res.data
            }
          })
        } else {
          this.codeMsg = '手机号码有误，更改登录手机号请联系</br>本机构管理员或者李老师(手机):177 3445 6101'
        }
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            // if(this.roleRadio){
            // 登录
            let data = {}
            if (this.countdown) {
              data = {
                loginStr: this.loginForm.username,
                password: '',
                // roleId: this.roleRadio,
                messageCode: this.loginForm.password,
              }
            } else {
              data = {
                loginStr: this.loginForm.username,
                password: this.loginForm.password,
                // roleId: this.roleRadio,
                messageCode: '',
              }
            }
            this.loading = true
            this.errorMsg = ''
            this.$store.dispatch('user/login', data).then(() => {
              this.$store.dispatch('user/getInfo')
              //拿到运动员名单，因为数据很多，后续请求页面会卡顿，提前拿到
              area2playerId().then(res => {
                // console.log(9);
                res.data.forEach(item => {
                  this.dict_player[item.playerId] = item.name
                })

                window.sessionStorage.setItem('playerdata', JSON.stringify(this.dict_player))
              })
              window.sessionStorage.setItem('roleId', this.roleRadio)
              window.sessionStorage.setItem('userId', this.userId)
              // 记住密码，应该记住token
              if (this.remember) {
                window.localStorage.setItem('username', this.loginForm.username)
                window.localStorage.setItem('password', this.loginForm.password)
              } else {
                window.localStorage.removeItem('username')
                window.localStorage.removeItem('password')
              }
              let provinceCheck = window.sessionStorage.getItem('provinceCheck')
              if (provinceCheck == 'true') {

                this.$router.push({ path: '/statistics/viewStatistics' })



                window.sessionStorage.setItem('statisticsMenu', true)
              } else {
                this.$message.warning('请您前往体校系统登录')
              }
              this.loading = false
            }).catch((err) => {
              this.errorMsg = '账号或密码错误'
              this.passwordvalid = true
              this.loading = false
            })
            // }else{
            //   this.roleColor = true
            // }
          } else {
            return false
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $light_gray: #000000;
  $cursor: #000000;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0;
        -webkit-appearance: none;
        border-radius: 4px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;
      }
    }

    .el-form-item {
      border: 1px solid rgba(2, 1, 1, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg: #0da883;
  $dark_gray: #889aa4;
  $light_gray: #000000;

  .login-container {
    min-height: 100%;
    width: 100%;
    background-image: url('../../assets/img/back.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: absolute;

    .title {
      font-size: 36px;
      padding: 20px;
    }

    .top-icon {
      width: 50px;
      height: 50px;
      background-color: $bg;
      color: #ffffff;
      margin-left: auto;
      border-radius: 5px;
      transform: translateY(5px);
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .login-form {
      width: 520px;
      min-height: 345px;
      padding: 50px 35px 0;
      margin: 0 auto;
      overflow: hidden;
      background-color: #ffffff;
      border-radius: 5px;
      border-top: 5px solid $bg;

      .border {
        height: 1px;
        width: 85%;
        background-image: linear-gradient(to right, #fff, #c7c7c7, #fff);
        margin: 20px auto;
      }
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }
  }
</style>
